import { defineStore } from 'pinia';
import { Local } from '/@/utils/storage';
import { login, logout } from '/@/api/login';
import { menuAuth } from '/@/api/auth/menu';
import { getToken, setToken, clearAuthInfo } from "/@/stores/auth";

interface UserInfosState {
	token: any;
	userInfos: any;
}

interface LoginParams {
	account: string;
	password: string;
	channel: number;
	code?: string;
	captchaUniqid?: string;
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		token: "",
		userInfos: {
			userName: '',
			time: 0,
			roles: [],
			is_auth: false,
			authBtnList: [],
		},
	}),
	getters: {
	},
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Local.get('userInfo')) {
				this.userInfos = Local.get('userInfo');
			}
		},
		async login(params: LoginParams) {
			const res = await login(params);
			// 存储 token 到浏览器缓存
			setToken(res.token);
			// 用户信息数据
			const userInfos = {
				userName: res.name,
				time: new Date().getTime(),
				roles: ["admin"],
				authBtnList: [],
			};
			// 存储用户信息到浏览器缓存
			Local.set('userInfo', userInfos);
			this.userInfos = userInfos;
			return userInfos;
		},
		async logout() {
			await logout();
			clearAuthInfo();
		},
		async getAuthMenu() {
			// 权限数据
			if(getToken()) {
				const res = await menuAuth(); 
				this.userInfos.authBtnList = res.authBtnList;
				this.userInfos.is_auth = true;
				const localInfo = Local.get('userInfo');
				if (localInfo) {
					localInfo['authBtnList'] = res.authBtnList;
					localInfo['is_auth'] = true;
					Local.set('userInfo', localInfo);
				}
			}
		},
	},
});
